// pages/dphb/dphb.js
// pages/dpinfo/dpinfo.js
import Wxml2Canvas from 'wxml2canvas'
import instance from "../../utils/util"


Page({

    /**
     * 页面的初始数据
     */
    data: {
        shop: {},
        width:"",
        height:"",
        imgUrl:"",
        shareImg: "",
        canvasHidden: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getinfo(options.id)
    },
  async  save() {
      let that=this;
    const query = wx.createSelectorQuery().in(this);
    query.select('#hb').fields({ // 选择需要生成canvas的范围
        size: true,
        scrollOffset: true
    }, data => {
        let width = data.width;
        let height = data.height;
        that.setData({
            width,
            height
        })
        setTimeout(() => {
            that.startDraw()
        }, 1500);
   }).exec()

    },
    startDraw() {
        let that = this
         
        // 创建wxml2canvas对象
        let drawMyImage = new Wxml2Canvas({
          element: 'share', // canvas的id,
          obj: that, // 传入当前组件的this
          width: that.data.width * 2,
          height: that.data.height * 2,
        background:"#d8b575",
          progress(percent) { // 进度
            // console.log(percent);
          },
          finish(url) { // 生成的图片
            console.log(url)
            wx.hideLoading()
            that.savePoster(url)
          },
          error(res) { // 失败原因
            console.log(res);
            wx.hideLoading()
          }
        }, this);
        let data = {
            // 获取wxml数据
            list: [{
                type: 'wxml',
                class: '.hb .hb_draw',  // my_canvas要绘制的wxml元素根类名， my_draw_canvas单个元素的类名（所有要绘制的单个元素都要添加该类名）
                limit: '.hb', // 要绘制的wxml元素根类名
                x: 0,
                y: 0
            }]
        }
        // 绘制canvas
        drawMyImage.draw(data, this);
    },
    savePoster(url) {
        const that = this
        wx.saveImageToPhotosAlbum({
            filePath: url,
            success: function() {
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    duration: 1500
                });
            },
            fail(err) {
                console.log(err)
            }
        })
    },
    async getinfo(id) {
        const res = await instance.get("/api/shops/" + id);
        console.log(res)
        this.setData({
            shop: res.data
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})